import { of, Subscription, filter, mergeMap, from, map } from "rxjs";
import { OperatorManager } from "../../operators/operatorManager";
import { RunTime } from "../../runtime";
import { BaseController } from "../baseController";
import { EventClass } from "@lib/alen-helper/node/baseClass";
import { get_back_observable } from "@lib/alen-helper/node/fun";


export class TrayController extends BaseController<'tray', {
    'click': { item: OperatorManager.Item<'tray'> },
    'double-click': { item: OperatorManager.Item<'tray'> },
}> {
    constructor(
        private _runTime: RunTime,
        BaseOptions?: Partial<EventClass.BaseOptions>,
    ) {
        super('TrayController', 'tray', _runTime.operatorManager, BaseOptions);
        this._sub();
    }

    private _subs: Subscription | null = null;
    private _unSub() {
        if (this._subs) this._subs.unsubscribe();
        this._subs = null;
    }
    private _sub() {
        this._subs = this.event('build')
            .subscribe(data => {
                const subs = data.item.operator.event('destroy')
                    .subscribe(() => {
                        subs.unsubscribe();
                    });
                subs.add(
                    data.item.operator.event('double-click')
                        .subscribe(e => {
                            this.triggerEvent('double-click', { item: data.item });
                        })
                );
                subs.add(
                    data.item.operator.event('click')
                        .subscribe(e => {
                            this.triggerEvent('click', { item: data.item });
                        })
                );
            });
    }

    setIcon(appid: string, id: string, icon: Runtime.OperatorCls.Tray.Options["icon"]) {
        const item = this.getOperator(appid, id);
        if (!item) return of(false);
        return get_back_observable(item.operator.setIcon(icon));
    }

    setToolTip(appid: string, id: string, toolTip: Runtime.OperatorCls.Tray.Options["toolTip"]) {
        const item = this.getOperator(appid, id);
        if (!item) return of(false);
        return get_back_observable(item.operator.setToolTip(toolTip));
    }

}